/**
 * Created by Administrator on 2017/11/28 0028.
 */
import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Row,
  Col,
  Button,
  DatePicker,
  message,
  TreeSelect,
  Modal,
  Table,
  Alert
} from "antd";
import moment from "moment";
import "./less/personnel.less";
import * as ajax from "../../../services/api";

const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;

@Form.create()
export default class BasicInformationPage extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      addpeoplevisible: false,
      addpeoplevisible1: false,
      dataSource: [],
      // comId:1,
      confirmDirty: false,
      basicInFormaation: {
        name: "",
        mobilePhone: "",
        idCardType: "1",
        idCardNo: "",
        roleId: [],
        entryDate: null,
        departId: "",
        isAppActive: "0",
        roleType: ""
      },
      perId: "", //用户id
      idCardType: [],
      roldType: [], //角色下拉选择
      treeData: [
        //树
        { title: "", key: "" }
      ],
      roleId: "",
      selectedRowKeys: "",
      pagenav: {
        current: 1,
        pageSize: 5000,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = current;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.systemComDepartPage();
          });
        },
        onChange: (page, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = page;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav });
          setTimeout(() => {
            this.systemComDepartPage();
          });
        },
        total: 0
      }
    };
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    this.renderIdcardType();
    this.roldList();
    this.departList();
    const { setFieldsValue } = this.props.form;
    this.comInsGetComInsPage();
    setTimeout(() => {
      console.log(this.state.basicInFormaation, "this.state.basicInFormaation");
      setFieldsValue({ mobilePhone: this.state.basicInFormaation.mobilePhone });
    }, 5000);
  }

  componentWillReceiveProps(props) {
    if (
      props.perId !== undefined &&
      props.perId !== "" &&
      props.perId !== this.props.perId
    ) {
      this.setState({
        perId: props.perId
      });
      ajax.systemPerBaseInfoGetPerBaseInfo({ perId: props.perId }).then(
        data => {
          console.log(data, "用户信息-data");
          const roleId = data.data.roleId ? data.data.roleId.split(",") : [];

          this.setState({
            basicInFormaation: {
              name: data.data.name,
              idCardType: data.data.idCardType || "1",
              mobilePhone: data.data.mobilePhone,
              idCardNo: data.data.idCardNo,
              departId: data.data.orgId,
              entryDate: data.data.entryDate,
              isAppActive: data.data.isAppActive || "0",
              roleType: data.data.roleType || "",
              roleId
            },
            roleId
          });
        },
        err => {
          console.log("errerr", err);
        }
      );
    }
  }

  //证件类型选择
  renderIdcardType = () => {
    ajax.getDictInformation({ codeTypes: "idCardType" }).then(data => {
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          idCardType: data.data.idCardType
        });
      }
    });
  };

  //提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.entryDate = values["entryDate"].format("YYYY-MM-DD");
        if (
          !/(1|2|3)/.test(this.state.basicInFormaation.roleType) ||
          this.state.basicInFormaation.roleType !== ""
        ) {
          if (values.roleId !== undefined) {
            values.roleId = values.roleId.join(",");
          } else {
            values.roleId = "";
          }
        } else {
          values.roleId = this.state.roleId;
        }
        if (this.state.perId !== "") {
          //修改
          values.perId = this.state.perId;
          ajax
            .systemPerBaseInfoUpdateBaseInfo({ ...values })
            .then(res => {
              console.log(res, "修改基础信息-res");
            })
            .catch(err1 => console.log(err1, "修改基础信息-err1"));
        } else {
          //新增
          ajax
            .systemPerBaseInfoSaveBaseInfo({ ...values })
            .then(res => {
              this.props.handleChangeTab();
              this.props.getId(res.data);
              if (this.state.dataSource.length > 0) {
                this.setState({
                  // 保险增员提示
                  perId: res.data,
                  addpeoplevisible: true
                });
              }
            })
            .catch(err2 => console.log(err2, "添加人员-err2"));
        }
      }
    });
  };

  checkPassword = (rule, value, callback) => {
    const { form } = this.props.form;
    if (value && value !== form.getFieldValue("password")) {
      callback("Two passwords that you enter is inconsistent!");
    } else {
      callback();
    }
  };
  checkConfirm = (rule, value, callback) => {
    const { form } = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(["confirm"], { force: true });
    }
    callback();
  };

  handleClick() {
    console.log(this);
  }

  renderIdCard = () => {
    return this.state.idCardType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  //发送激活短信
  sendActivationSMS = () => {
    const { form } = this.props;
    const phoneValue = form.getFieldValue("mobilePhone");
    if (phoneValue === "") {
      message.error("手机号码不能为空！");
    } else if (!/^1[0-9]{10}$/.test(phoneValue)) {
      message.error("手机号码格式不正确！");
    } else {
      ajax
        .systemPlatNewsSendActivationMessage({ mobile: phoneValue })
        .then(data => {
          if (data.data) {
            message.success(data.data);
          }
        });
    }
  };

  //验证证件号
  checkIdCardNo = (rule, value, callback) => {
    const { form } = this.props;
    const cardNoValue = form.getFieldValue("idCardType");
    if (
      cardNoValue === "1" &&
      value &&
      !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)
    ) {
      callback("请输入正确的身份证号码！");
    } else {
      callback();
    }
  };

  //角色下拉选择
  roldList = () => {
    ajax.systemComRoleFindAllRole({}).then(data => {
      console.log("角色下拉选择data:", data);
      //判断获取数据是否为空
      if (data.data) {
        this.setState({
          roldType: data.data
        });
      }
    });
  };

  //角色下拉选择
  renderInstitution = () => {
    return this.state.roldType.map((val, key) => {
      return (
        <Option key={key} value={val.roleId + ""}>
          {val.roleName}
        </Option>
      );
    });
  };

  comInsGetComInsPage = () => {
    const { pagenav } = this.state;
    ajax
      .comInsGetComInsPage({
        pageSize: pagenav.pageSize,
        pageNumber: pagenav.current,
        buyMode: "1"
      })
      .then(res => {
        console.log(res, "保险分页-res");
        const dataSource = res.data.data.map(val => {
          val.key = val.blbOrderId;
          return val;
        });
        this.setState({ dataSource });
      })
      .catch(err => console.log(err));
  };

  //保全链接生成
  enterpriseInsComInsGetOnlineInsBlbPreservationLink = () => {
    ajax
      .enterpriseInsComInsGetOnlineInsBlbPreservationLink({
        orderId: this.state.selectedRowKeys,
        perIds: this.state.perId,
        reviseType: "1"
      })
      .then(res => {
        console.log(res, "保全链接生成-res");
        this.setState({ addpeoplevisible1: false });
        this.newwin.location.href = res.data;
      })
      .catch(err => {
        this.newwin.close();
        this.setState({ addpeoplevisible1: false });
        console.log(err, "保全链接生成-err");
      });
  };

  //选择部门
  departList = () => {
    ajax.systemComDepartGetTreeDepart().then(
      response => {
        console.log(response, "getTreeDepart-选择部门-response");
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        this.setState({
          treeData: data,
          departId: data[0].key
        });
      },
      err => {
        console.log(err, "getTreeDepart-选择部门-err");
      }
    );
  };

  renderBack = () => {
    const that = this;
    if (that.state.isBack) {
      that.props.props.history.push(`/Organization/departmentmanagement`);
    } else {
      confirm({
        title: "当前信息未提交，是否确认返回？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          that.props.props.history.push(`/Organization/departmentmanagement`);
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };

  //保险选择
  renderTable = () => {
    const rowSelection = {
      type: "radio",
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: selectedRowKeys => {
        this.setState({ selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === "Disabled User" // Column configuration not to be checked
      })
    };
    const columns = [
      {
        title: "订单号",
        dataIndex: "blbOrderId",
        key: "blbOrderId"
      },
      {
        title: "保险产品",
        dataIndex: "insComName",
        key: "insComName"
      },
      {
        title: "人数",
        dataIndex: "perNum",
        key: "perNum"
      },
      {
        title: "购买时间",
        dataIndex: "effectStartDate",
        key: "effectStartDate"
      }
      /* {
        title: "保费(元)",
        dataIndex: "effectStartDate",
        key: "effectStartDate"
      } */
    ];

    return (
      <Table
        size="middle"
        width={800}
        rowSelection={rowSelection}
        columns={columns}
        pagination={false}
        dataSource={this.state.dataSource}
      />
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // const { autoCompleteResult } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 }
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 6
        }
      }
    };

    const phFormItemLayout = {
      labelCol: {
        xs: { span: 16 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 12 }
      }
    };
    const spanStyle = {
      color: "#909CA8"
    };
    const clickStyle = {
      color: "#1890ff",
      cursor: "pointer"
    };
    const msg =
      this.state.basicInFormaation.isAppActive === "0" ? (
        <p>
          <span style={spanStyle}>
            首次导入人员信息，默认发送短信通知该用户激活帐号。未收到可再次点击
          </span>
          <span onClick={this.sendActivationSMS} style={clickStyle}>
            {" "}
            "发送激活短信"
          </span>
        </p>
      ) : (
        ""
      );
    return (
      <div className="BasicInformationPage clearfloat PersonnelGeneralStyle">
        <div className="basic-right general-main">
          <div className="from-box">
            <Form onSubmit={this.handleSubmit}>
              <FormItem
                className="head-portrait"
                {...formItemLayout}
                label="头像"
              >
                <div className="pic" />
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="姓名"
                className="fixed-width"
              >
                {getFieldDecorator("name", {
                  initialValue: this.state.basicInFormaation.name,
                  rules: [
                    { required: true, message: "请输入你的姓名!" },
                    {
                      validator: (rule, value, cb) => {
                        if (
                          value.length > 0 &&
                          !/^[\u4E00-\u9FA5A-Za-z]+$/.test(value)
                        ) {
                          cb("请输入英文或汉字!");
                        }
                        cb();
                      }
                    }
                  ]
                })(
                  <Input
                    className="w-400"
                    placeholder="请输入"
                    maxLength="16"
                  />
                )}
              </FormItem>
              <FormItem
                {...phFormItemLayout}
                label="手机号"
                className="fixed-width"
                extra={msg}
              >
                <Row gutter={24}>
                  <Col span={24}>
                    {getFieldDecorator("mobilePhone", {
                      initialValue: this.state.basicInFormaation.mobilePhone,
                      rules: [
                        { required: true, message: "请输入手机号码!" },
                        {
                          validator: (rule, value, cb) => {
                            if (value && !/^1[0-9]{10}$/.test(value)) {
                              cb("请输入正确手机号码!");
                            }
                            cb();
                          }
                        }
                      ]
                    })(
                      <Input
                        className="w-400 ipt-h"
                        placeholder="请输入"
                        disabled={
                          this.state.basicInFormaation.isAppActive === "0"
                            ? 0
                            : true
                        }
                      />
                    )}
                  </Col>
                  <Col span={4} className="verification-code" />
                </Row>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="证件类型"
                className="document-type lmb-sd"
              >
                {getFieldDecorator("idCardType", {
                  initialValue: this.state.basicInFormaation.idCardType,
                  rules: [{ required: true, message: "请选择证件类型!" }]
                })(
                  <Select
                    placeholder="请选择"
                    style={{ width: "400px" }}
                    onChange={this.handleChangeIdCardType}
                  >
                    {this.renderIdCard()}
                  </Select>
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="证件号码"
                className="fixed-width certificate-number"
              >
                {getFieldDecorator("idCardNo", {
                  initialValue: this.state.basicInFormaation.idCardNo,
                  rules: [
                    { required: true, message: "请输入证件号!" },
                    { validator: this.checkIdCardNo }
                  ]
                })(
                  <Input
                    className="w-400"
                    placeholder="请填写证件号码"
                    maxLength="20"
                  />
                )}
              </FormItem>
              {console.log(
                this.state.basicInFormaation,
                "this.state.basicInFormaation"
              )}
              {!/(1|2|3)/.test(this.state.basicInFormaation.roleType) ||
              this.state.basicInFormaation.roleType === "" ? (
                <FormItem
                  {...formItemLayout}
                  label="角色"
                  className="fixed-width"
                >
                  {getFieldDecorator("roleId", {
                    initialValue: this.state.basicInFormaation.roleId,
                    rules: [
                      {
                        required: false,
                        message: "请选折你要的角色1",
                        type: "array"
                      }
                    ]
                  })(
                    <Select
                      mode="multiple"
                      placeholder="请选择角色"
                      className="w-400 ipt-h"
                    >
                      {this.renderInstitution()}
                    </Select>
                  )}
                </FormItem>
              ) : (
                ""
              )}
              {this.state.departId ? (
                <FormItem
                  {...formItemLayout}
                  label="所属部门"
                  className="fixed-width"
                >
                  {getFieldDecorator("departId", {
                    initialValue: this.state.basicInFormaation.departId,
                    rules: [{ required: true, message: "请选择所属部门" }]
                  })(
                    <TreeSelect
                      className="w-400 ipt-h"
                      dropdownStyle={{ maxHeight: 250, overflow: "auto" }}
                      treeData={this.state.treeData}
                      placeholder="请选择部门"
                      treeDefaultExpandAll
                    />
                  )}
                </FormItem>
              ) : (
                <FormItem
                  {...formItemLayout}
                  label="所属部门"
                  className="fixed-width"
                >
                  {getFieldDecorator("departId", {
                    rules: [{ required: true, message: "请选择所属部门" }]
                  })(
                    <TreeSelect
                      className="w-400 ipt-h"
                      dropdownStyle={{ maxHeight: 250, overflow: "auto" }}
                      treeData={this.state.treeData}
                      placeholder="请选择部门"
                      treeDefaultExpandAll
                    />
                  )}
                </FormItem>
              )}

              {this.state.basicInFormaation.entryDate ? (
                <FormItem
                  {...formItemLayout}
                  label="入职日期"
                  className="fixed-width"
                >
                  {getFieldDecorator("entryDate", {
                    initialValue: moment(
                      this.state.basicInFormaation.entryDate,
                      "YYYY-MM-DD"
                    ),
                    rules: [{ required: true, message: "请选择日期!" }]
                  })(<DatePicker className="w-400" />)}
                </FormItem>
              ) : (
                <FormItem
                  {...formItemLayout}
                  label="入职日期"
                  className="fixed-width"
                >
                  {getFieldDecorator("entryDate", {
                    rules: [{ required: true, message: "请选择日期!" }]
                  })(<DatePicker className="w-400" />)}
                </FormItem>
              )}

              <FormItem {...tailFormItemLayout}>
                <Button
                  style={{ marginRight: "8px" }}
                  onClick={this.renderBack}
                >
                  返回
                </Button>
                {this.state.perId === "" ? (
                  <Button type="primary" htmlType="submit">
                    确认新增
                  </Button>
                ) : (
                  <Button type="primary" htmlType="submit">
                    确认修改
                  </Button>
                )}
              </FormItem>
            </Form>
            <Modal
              className="reducepeople"
              title="保险员增员提示"
              visible={this.state.addpeoplevisible}
              onOk={this.handlereducepeopleOk}
              onCancel={() => this.setState({ addpeoplevisible: false })}
              footer={[
                <Button
                  key="cancel"
                  onClick={() => this.setState({ addpeoplevisible: false })}
                >
                  取消
                </Button>,
                <Button
                  key="submit"
                  type="primary"
                  onClick={() => {
                    this.setState({
                      addpeoplevisible: false,
                      addpeoplevisible1: true
                    });
                  }}
                >
                  马上办理
                </Button>
              ]}
            >
              <div>
                <div>
                  <Alert
                    message="保险产品的增员、减员、替换等操作可通过【金融保险】-【保险订单】-选择有效订单的【保全】对保单中的人员增减操作！"
                    type="warning"
                    showIcon
                  />
                </div>
                <p>
                  本次新增人员共1
                  位，企业目前已购买团意险产品[产品名称]（订单号：[订单编号]），企业可对新增人员办理保险保全的增员操作。
                </p>
              </div>
            </Modal>

            <Modal
              width={1000}
              title="选择订单"
              visible={this.state.addpeoplevisible1}
              onCancel={() => this.setState({ addpeoplevisible1: false })}
              footer={[
                <Button
                  key="submit1"
                  onClick={() => {
                    this.setState({ addpeoplevisible1: false });
                  }}
                >
                  取消
                </Button>,
                <Button
                  key="submit"
                  type="primary"
                  onClick={() => {
                    if (!this.state.selectedRowKeys) {
                      message.error("请选择订单");
                      return null;
                    }
                    this.newwin = window.open("about:blank");
                    this.enterpriseInsComInsGetOnlineInsBlbPreservationLink();
                  }}
                >
                  确认
                </Button>
              ]}
            >
              {this.renderTable()}
            </Modal>
          </div>
        </div>
      </div>
    );
  }
}
